package br.com.fiap.fiappizzas.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import br.com.fiap.fiappizzas.db.entities.Address;
import br.com.fiap.fiappizzas.db.entities.Client;

public class ClientDAO extends AbstractDAO<Client> {
	
	final AddressDAO addressDAO;

	public ClientDAO(Context context) {
		super(context);
		addressDAO = new AddressDAO(context);
	}

	@Override
	public String getTableName() {
		return "tb_client";
	}

	@Override
	public String[] getColumns() {
		return new String[]{"id", "name", "address", "phone"};
	}

	@Override
	public Client buildEntity(Cursor cursor) {
		
		final Client c = new Client();
		
		c.setId(cursor.getLong(0));
		c.setName(cursor.getString(1));
		
		Address address = addressDAO.getEntityById(cursor.getLong(2));
		
		c.setAddress(address);
		c.setPhone(cursor.getString(3));
		
		return c;
		
	}

	@Override
	public ContentValues buildContentValues(Client entity) {
		final ContentValues values = new ContentValues();
        
		values.put("id", entity.getId());  
        values.put("name", entity.getName());

        if (entity.getAddress() != null) {
        	values.put("address", entity.getAddress().getId());
        }
        
        values.put("phone", entity.getPhone());
        
        return values;
	}

	@Override
	public Client insert(Client entity) {
		Address address = addressDAO.insert(entity.getAddress());
		entity.setAddress(address);
		return super.insert(entity);
	}
	
	public Client getByPhone(Long phoneNumber) {
		
		final SQLiteDatabase db = getReadableDB();
		
		Cursor cursor = 
	            db.query(getTableName(),
	            getColumns(),
	            " phone = ?", 
	            new String[] { String.valueOf(phoneNumber) },
	            null,
	            null,
	            null,
	            null);
	 
		if (cursor != null && cursor.getCount() != 0) {
			cursor.moveToFirst();
	 
		    Client entity = buildEntity(cursor);
		 
		    Log.d("getEntityByPhone("+phoneNumber+")", entity.toString());
		    
		    return entity;
		}
	 
		return null;
	}
}
